var app  = require('express')();
var http = require('http').Server(app);
var io   = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
    res.sendFile(__dirname + '/chat.html');
});

var users   = new Array();
var sockets = [];
io.on('connection', function(socket){
    socket.on('join', function(username, user_img){
        for(i in users) {
            if (users[i].un == username) {
                socket.emit('exists');
                return false;
            }
        }

        users.push({
            un:username, 
            ui:user_img, 
            time:new Date().toLocaleString()
        });

        socket.username = username;
        sockets[username] = socket;
        io.emit('join', users);
        console.log('user connected');
    });

    socket.on('send', function(username, user_img, to_user, to_img, message){
        if (to_user == '' || to_user == '所有人') {
            io.emit('display', username, user_img, to_user, to_img, message);
        } else {
            var myself = sockets[username];
            var target = sockets[to_user];
            if (myself) {
                myself.emit('display', username, user_img, to_user, to_img, message);
            }
            // 私聊自己时不推送相同消失
            if (target && username != to_user) {
                target.emit('display', username, user_img, to_user, to_img, message);
            }
        }
    });

    socket.on('disconnect', function(){
        for(i in users) {
            if (users[i].un == socket.username) {
                users.splice(i, 1);
                break;
            }
        }
        io.emit('left', users);
        console.log('user disconnected');
    });
});

http.listen(port, function(){
    console.log('Server listening at port %d', port);
});